﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Odbc;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace Derbster.Peer.Sender
{
    public class MessageSender : IMessageSender
    {
        private static MessageQueue _messageQueue;
        private static string _msmqFormat; 

        public MessageSender()
        {
           
        }

        public void AddPeer(string ipAddress, string peerId)
        {
            if (_msmqFormat == null)
            {
                _msmqFormat = String.Format("FormatName:DIRECT=TCP:{0}\\private$\\Derbster_{1}", ipAddress, peerId);
            }
            else
            {
                _msmqFormat += String.Format(",DIRECT=TCP:{0}\\private$\\Derbster_{1}", ipAddress, peerId);
            }

            if (_messageQueue != null) _messageQueue.Dispose();
            _messageQueue = new MessageQueue(_msmqFormat, QueueAccessMode.Send);
            _messageQueue.SetFormatter<PeerMessage>();
        }

        public void SendMessage(PeerMessage message)
        {
            if (_messageQueue == null)
            {
                return;
            }

            message.PeerId = PeerContext.PeerId;
            message.TimeStamp = DateTime.UtcNow;

            var queueMessage = new Message(message);

            PeerContext.CurrentVectorClock.Increment();
            _messageQueue.Send(queueMessage);
        }
    }
}
